package com.rc.fragment;

import java.io.InputStream;
import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.artifex.mupdfdemo.MuPDFActivity;
import com.rc.activity.R;
import com.rc.activity.ReceiptBox;
import com.rc.activity.ReceiptBox.OnBackPressedListener;
import com.rc.activity.ReceiptBoxDetailAddItem;
import com.rc.activity.ReceiptConverter;
import com.rc.activity.ReceiptMerchantInfo;
import com.rc.activity.TripList;
import com.rc.activity.dao.tbl_Item;
import com.rc.activity.dao.tbl_Receipt;
import com.rc.activity.dao.tbl_ReceiptDao;
import com.rc.activity.provider.Contract;
import com.rc.adapter.ReceiptDetailAdapter;
import com.rc.custom.MyListView;
import com.rc.db.DatabaseSupport;
import com.rc.net.NetSupport;
import com.rc.net.NetUtils;
import com.rc.object.BaseObject;
import com.rc.object.ReceiptObj;
import com.rc.util.Const;
import com.rc.util.Util;
import com.telpoo.frame.model.BaseModel;
import com.telpoo.frame.ui.BaseFragment;
import com.telpoo.frame.utils.Utils;

@SuppressLint("ValidFragment")
public class ReceiptDetailFragment extends BaseFragment implements
		OnBackPressedListener, OnClickListener {

	private TextView txtSelect, txtMerchantDate, txtMerchantAddress,
			txtSubTotal, txtDiscount, txtTax, txtMoney, txtMerchantName;
	private ReceiptObj receiptObj;
	private LinearLayout llTitle, llConverter, llSubtotal, llViewPhoto,
			llDelete, llFuntion, llDeleteAndCancel, llCancel, llActionDelete,
			llContent;
	private RelativeLayout rlTotal, rlAddNew, rlSelect, rlCategorize;
	private ProgressBar pbLoad;
	private MyListView mgvReceiptList;
	private ReceiptDetailAdapter adpReceiptDetail;
	private Dialog dialog;
	private ImageView imgArrow, imgAllReceipt, imgViewLogo, imgAddress;
	private boolean isCheck = true;
	private boolean isShow = true;
	private long mReceiptID;
	private ArrayList<tbl_Item> arrItem;
	private tbl_Receipt objReceipt;
	private int mReceiptKey;
	private int mCountReceipt;
	private int numberFilter;
	private float subtotal = 0;
	private float tax = 0;
	private float discount = 0;
	private float total = 0;

	public ReceiptDetailFragment() {
		super();
	}

	public ReceiptDetailFragment(long mReceiptID, int mReceiptKey,
			int mCountReceipt, int numberFilter) {
		super();
		this.mReceiptKey = mReceiptKey;
		this.mReceiptID = mReceiptID;
		this.mCountReceipt = mCountReceipt;
		this.numberFilter = numberFilter;
	}

	View v = null;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		v = (ViewGroup) inflater.inflate(R.layout.receiptdetail, null);

		// Register
		llTitle = (LinearLayout) v.findViewById(R.id.llTitle);
		llConverter = (LinearLayout) v.findViewById(R.id.llConverter);
		llFuntion = (LinearLayout) v.findViewById(R.id.llFuntion);
		llContent = (LinearLayout) v.findViewById(R.id.llContent);
		llActionDelete = (LinearLayout) v.findViewById(R.id.llActionDelete);
		llDeleteAndCancel = (LinearLayout) v
				.findViewById(R.id.llDeleteAndCancel);
		pbLoad = (ProgressBar) v.findViewById(R.id.pbLoad);
		imgAddress = (ImageView) v.findViewById(R.id.imgAddress);
		mgvReceiptList = (MyListView) v.findViewById(R.id.mgvReceiptList);
		llSubtotal = (LinearLayout) v.findViewById(R.id.llsubtotal);
		llCancel = (LinearLayout) v.findViewById(R.id.llCancel);
		rlTotal = (RelativeLayout) v.findViewById(R.id.rlTotal);
		rlAddNew = (RelativeLayout) v.findViewById(R.id.rlAddNew);
		rlSelect = (RelativeLayout) v.findViewById(R.id.rlSelect);
		rlCategorize = (RelativeLayout) v.findViewById(R.id.rlCategorize);
		imgArrow = (ImageView) v.findViewById(R.id.imgArrow);
		llViewPhoto = (LinearLayout) v.findViewById(R.id.llViewPhoto);
		llDelete = (LinearLayout) v.findViewById(R.id.llDelete);
		txtSelect = (TextView) v.findViewById(R.id.txtSelect);
		imgAllReceipt = (ImageView) v.findViewById(R.id.imgAllReceipt);
		txtMerchantAddress = (TextView) v.findViewById(R.id.txtMerchantAddress);
		txtMerchantDate = (TextView) v.findViewById(R.id.txtMerchantDate);
		txtSubTotal = (TextView) v.findViewById(R.id.txtSubTotal);
		txtDiscount = (TextView) v.findViewById(R.id.txtDiscount);
		txtTax = (TextView) v.findViewById(R.id.txtTax);
		txtMoney = (TextView) v.findViewById(R.id.txtMoney);
		txtMerchantName = (TextView) v.findViewById(R.id.txtMerchantName);
		imgViewLogo = (ImageView) v.findViewById(R.id.imgViewLogo);

		// Function
		llTitle.setOnClickListener(this);
		llActionDelete.setOnClickListener(this);
		llConverter.setOnClickListener(this);
		llSubtotal.setOnClickListener(this);
		rlTotal.setOnClickListener(this);
		llViewPhoto.setOnClickListener(this);
		llDelete.setOnClickListener(this);
		rlAddNew.setOnClickListener(this);
		rlSelect.setOnClickListener(this);
		llCancel.setOnClickListener(this);
		rlCategorize.setOnClickListener(this);

		return v;
	}

	@Override
	public void onResume() {
		super.onResume();

		((ReceiptBox) getActivity())
				.setOnBackPressedListener(new ReceiptDetailFragment(mReceiptID,
						mReceiptKey, mCountReceipt, numberFilter));
		((ReceiptBox) getActivity()).setBackground(
				R.color.background_title_receipt, getResources());
		((ReceiptBox) getActivity())
				.setTitle(getString(R.string.receipt_details));
		((ReceiptBox) getActivity()).setLogo(R.drawable.ic_top_receiptbox);
		addDataUI();
		cancelMultiSelect();
	}

	private void getTbl_item() {
		arrItem = new ArrayList<tbl_Item>();
		arrItem = DatabaseSupport.getItemsByReceiptID(mReceiptID + "",
				getActivity());
	}

	/**
	 * get data on SQLite
	 */
	private void getDataSQLite() {
		// resset subtotal
		subtotal = 0;
		// Get tbl_Receipt by Receipt_ID

		objReceipt = new tbl_Receipt();
		objReceipt = DatabaseSupport.getReceiptByID(mReceiptID, getActivity());
		// Convert tbl_Receipt to ReceiptObj
		receiptObj = new ReceiptObj();
		receiptObj = DatabaseSupport.convertReceiptObj(objReceipt,
				getActivity());

		// get all tbl_Item by receipt ID
		getTbl_item();
		if (arrItem != null) {
			for (tbl_Item objItem : arrItem) {
				subtotal = subtotal + Util.convertFloat(objItem.getAmount());
			}
		}
		if (receiptObj == null) {
			return;
		}
		if (!receiptObj.getSubTotal().equals(subtotal + "")) {

			float mSubTotal = 0;
			mSubTotal = Util.convertFloat(receiptObj.getTotal())
					- Util.convertFloat(receiptObj.getTax())
					+ Util.convertFloat(receiptObj.getDiscount());
			if (Util.convertFloat(mSubTotal + "") > Util.convertFloat(subtotal
					+ "")) {
				// create new Item nếu subtotal của receipt lớn hơn subtotal của
				// item
				tbl_Item objItem = new tbl_Item();
				objItem.setItemID(Long.valueOf(Util.getCurrentTime()));
				objItem.setName("Item");
				objItem.setAmount(Util.formatStringFloat(mSubTotal - subtotal));
				long tripID = 0;
				objItem.setTripID(tripID);
				objItem.setIsCreate("1");
				objItem.setIsDelete("");
				objItem.setIsUpdate("");
				objItem.setReceiptID(mReceiptID);
				objItem.setMemo(getString(R.string.this_is_an_auto_updated_item));
				getActivity().getContentResolver().insert(
						Contract.CONTENT_URI_ITEMS, objItem.getContentValues());

				// get all tbl_Item by receipt ID
				getTbl_item();
			} else if (Util.convertFloat(mSubTotal + "") < Util
					.convertFloat(subtotal + "")) {
				// nếu subtotal của receipt mà nhỏ hơn subtotal cái mà được tính
				// bằng tổng số item thì update lại subtotal và total theo
				// subtotal của tổng số item
				receiptObj.setSubTotal(Util.formatStringFloat(subtotal));
				total = subtotal + Util.convertFloat(receiptObj.getTax())
						- Util.convertFloat(receiptObj.getDiscount());
				objReceipt.setSubtotal(Util.formatStringFloat(subtotal));
				objReceipt.setTotal(Util.formatStringFloat(total));
				objReceipt.setIsUpdate("1");
				getActivity().getContentResolver().update(
						Contract.CONTENT_URI_RECEIPT,
						objReceipt.getContentValues(),
						tbl_ReceiptDao.Properties.ReceiptID.columnName + " = "
								+ objReceipt.getReceiptID(), null);
			}

		}
	}

	/**
	 * insert data UI
	 */

	private void addDataUI() {
		getDataSQLite();

		// load Logo
		if (receiptObj == null) {
			return;
		}
		String logo = receiptObj.getMerchantLogo();
		new DisplayLogoMerchant(imgViewLogo).execute(logo);

		// fill data listview
		adpReceiptDetail = new ReceiptDetailAdapter(getActivity(), arrItem);
		mgvReceiptList.setAdapter(adpReceiptDetail);
		addDataTextView();

	}

	/**
	 * insert data textview UI
	 */
	private void addDataTextView() {
		if (receiptObj.getMerchantID() != 0) {
			txtMerchantAddress.setText(receiptObj.getAddress());
			txtMerchantName.setText(receiptObj.getMerchantName());
			imgAddress.setImageResource(R.drawable.ic_location);
		} else {
			txtMerchantAddress
					.setText(getString(R.string.please_update_merchant_name));
			txtMerchantName.setText(getString(R.string.merchant_unrecognized));
			txtMerchantAddress.setTextColor(getResources()
					.getColor(R.color.red));
			imgAddress.setImageResource(R.drawable.ic_warning);
		}

		txtMerchantDate.setText(receiptObj.getDateTime());

		if ("null".equals(objReceipt.getTotal())
				|| objReceipt.getTotal() == null) {
			txtMoney.setText("$0.00");
		} else {
			txtMoney.setText("$" + objReceipt.getTotal());
		}
		if ("null".equals(objReceipt.getDiscount())
				|| objReceipt.getDiscount() == null) {
			txtDiscount.setText("$0.00");
		} else {
			txtDiscount.setText("$" + objReceipt.getDiscount());
		}
		if ("null".equals(objReceipt.getTax()) || objReceipt.getTax() == null) {
			txtTax.setText("$0.00");
		} else {
			txtTax.setText("$" + objReceipt.getTax());
		}
		if ("null".equals(objReceipt.getSubtotal())
				|| objReceipt.getSubtotal() == null) {
			txtSubTotal.setText("$0.00");
		} else {
			txtSubTotal.setText("$" + objReceipt.getSubtotal());
		}
	}

	@Override
	public void doBack(Activity at) {
		ReceiptBox.obBackPress = null;
		Util.pushFragmentReceiptBox(new ReceiptFragment(mReceiptKey,
				mCountReceipt, numberFilter), (FragmentActivity) at, "3");
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.llTitle:
			ReceiptMerchantInfo.callIntentEdit(getActivity(),
					objReceipt.getMerchantID());
			break;
		case R.id.llConverter:
			ReceiptConverter.callIntent(getActivity(), receiptObj);
			break;
		case R.id.rlTotal:
			if (isShow) {
				animation(isShow);
				isShow = false;
			} else {
				animation(isShow);
				isShow = true;
			}
			break;
		case R.id.llViewPhoto:
			// ImageViewScreen.callIntentViewSDCard(getActivity(),
			// objReceipt.getReceiptID() + ".jpg");
			MuPDFActivity.callIntent(getActivity(), objReceipt.getReceiptID()
					+ ".pdf");
			break;
		case R.id.llDelete:
			if (DatabaseSupport.ruleRecipt(mReceiptID, getActivity())) {
				createDialogDelete();
			} else {
				createDialogError(true);
			}

			break;
		case R.id.rlAddNew:
			if (objReceipt == null) {
				return;
			}
			ReceiptBoxDetailAddItem.callItent(getActivity(),
					objReceipt.getReceiptID(), false);
			break;
		case R.id.rlSelect:
			visiableSelect(!adpReceiptDetail.isShowCheck);
			break;
		case R.id.llCancel:
			cancelMultiSelect();
			break;
		case R.id.rlCategorize:
			createDialogCategorize();
			break;
		case R.id.llCombined:
			setTextCategorize(getString(R.string.combined));
			ReceiptBoxDetailAddItem.callItentCombile(getActivity(), mReceiptID,
					Util.convertFloat(objReceipt.getSubtotal()));
			break;
		case R.id.llSelectedItem:
			setTextCategorize(getString(R.string.selected_item));
			break;
		case R.id.llAllitem:
			setTextCategorize(getString(R.string.allitem));
			break;
		case R.id.llsubtotal:

			if (DatabaseSupport.ruleRecipt(mReceiptID, getActivity())) {
				createDialogEditTotal();
			} else {
				createDialogError(false);
			}

			break;
		case R.id.llActionDelete:
			boolean isTrue = false;
			for (tbl_Item objItem : arrItem) {
				if (objItem.isCheck()) {
					isTrue = true;
					break;
				}
			}
			if (isTrue) {
				createDialogMultiDelete();
			} else {
				showToast(getString(R.string.please_select_one_item));
			}
			break;
		default:
			break;
		}
	}

	/**
	 * delete item
	 */
	/**
	 * dialog gá»“m 2 lá»±a chá»�n. user cÃ³ thá»ƒ chá»�n tá»›i pháº§n chá»¥p
	 * áº£nh hoáº·c user cÃ³ thá»ƒ chá»�n tá»›i sdcard
	 */

	private void createDialogMultiDelete() {
		dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_message);

		LinearLayout llOk, llCancel;
		((TextView) dialog.findViewById(R.id.txtTitle))
				.setText(getString(R.string.delete_receipt));
		String mContent = getString(R.string.are_you_sure_you_want_to_delete_item);
		((TextView) dialog.findViewById(R.id.txtContent)).setText(mContent);

		llOk = (LinearLayout) dialog.findViewById(R.id.llOk);
		llCancel = (LinearLayout) dialog.findViewById(R.id.llCancel);

		llOk.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				int row = 0;
				ArrayList<ContentValues> arrContentValues = new ArrayList<ContentValues>();

				for (int i = 0; i < arrItem.size(); i++) {
					if (arrItem.get(i).isCheck() == true) {
						arrItem.get(i).setIsDelete("1");
						arrContentValues.add(arrItem.get(i).getContentValues());

					}
				}
				row = DatabaseSupport.multiUpdate(objReceipt.getReceiptID(),
						arrContentValues, getActivity());
				if (row > 0) {
					// láº¥y giÃ¡ trá»‹ tá»« sqlite
					getDataSQLite();

					// noti listview
					adpReceiptDetail.notiB(arrItem);

					// fill data text
					addDataTextView();
				}

				dialog.dismiss();
			}
		});
		llCancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		dialog.show();

	}

	/**
	 * Show animation
	 */

	private void animation(boolean isShow) {
		Animation animation = null;
		if (isShow) {
			animation = (Animation) AnimationUtils.loadAnimation(getActivity(),
					R.anim.phone_in_bottom_animation);
			llSubtotal.setVisibility(View.VISIBLE);
			imgArrow.setImageResource(R.drawable.ic_arrow_down);
		} else {
			animation = (Animation) AnimationUtils.loadAnimation(getActivity(),
					R.anim.phone_in_top_animation);
			llSubtotal.setVisibility(View.GONE);
			imgArrow.setImageResource(R.drawable.ic_arrow_up);
		}
		llSubtotal.setAnimation(animation);
		llSubtotal.clearAnimation();
	}

	private void visiableSelect(boolean mIsSelect) {
		if (mIsSelect) {
			llFuntion.setVisibility(View.GONE);
			llDeleteAndCancel.setVisibility(View.VISIBLE);
			adpReceiptDetail.isShowCheck = true;
			isCheck = false;
			imgAllReceipt.setImageResource(R.drawable.ic_selectitem);
			txtSelect.setText(getString(R.string.select_all));
			adpReceiptDetail.notifyDataSetChanged();

		} else {
			setImgSelect(isCheck);

		}

	}

	private void cancelMultiSelect() {
		txtSelect.setText(getString(R.string.select));
		imgAllReceipt.setImageResource(R.drawable.ic_selectitem);
		llDeleteAndCancel.setVisibility(View.GONE);
		llFuntion.setVisibility(View.VISIBLE);
		adpReceiptDetail.isShowCheck = false;
		adpReceiptDetail.notifyDataSetChanged();
		toggleCheck(adpReceiptDetail.isShowCheck);
	}

	public void toggleCheck(Boolean val) {
		if (val == null) {
			return;
		}
		for (int i = 0; i < mgvReceiptList.getChildCount(); i++) {
			CheckBox cbMulti = null;
			cbMulti = (CheckBox) mgvReceiptList.getChildAt(i).findViewById(
					R.id.cbMulti);
			if (cbMulti != null) {
				cbMulti.setChecked(val);
			}

		}
	}

	/**
	 * setImage cho ImgAllReceipt vÃ  setText cho txtSelect
	 */
	private void setImgSelect(boolean isSelect) {
		toggleCheck(!isSelect);
		if (isSelect) {
			imgAllReceipt.setImageResource(R.drawable.ic_selectitem);
			txtSelect.setText(getString(R.string.select_all));
			isCheck = false;
			for (tbl_Item objItem : arrItem) {
				objItem.setCheck(false);
			}
		} else {
			imgAllReceipt.setImageResource(R.drawable.ic_selectall);
			txtSelect.setText(getString(R.string.unselect_all));
			isCheck = true;
			for (tbl_Item objItem : arrItem) {
				objItem.setCheck(true);
			}
		}

	}

	// show dialog choose categorize
	private void createDialogCategorize() {
		dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_receiptdetail_categorize);

		LinearLayout llAllitem, llSelectedItem;
		llAllitem = (LinearLayout) dialog.findViewById(R.id.llAllitem);
		llSelectedItem = (LinearLayout) dialog
				.findViewById(R.id.llSelectedItem);
		llAllitem.setOnClickListener(this);
		llSelectedItem.setOnClickListener(this);
		if (adpReceiptDetail.isShowCheck) {
			llSelectedItem.setVisibility(View.VISIBLE);
		}
		llAllitem.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				categorizeItem(true);
				dialog.dismiss();

			}
		});
		llSelectedItem.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				categorizeItem(false);
				dialog.dismiss();
			}
		});
		dialog.show();

	}

	// categorize Item
	private void categorizeItem(boolean isAll) {
		ArrayList<String> itemsID = new ArrayList<String>();
		for (int i = 0; i < arrItem.size(); i++) {
			if (isAll) {
				itemsID.add(arrItem.get(i).getItemID() + "");
			}
			if (arrItem.get(i).isCheck() == true) {
				itemsID.add(arrItem.get(i).getItemID() + "");

			}
		}
		if (itemsID.size() > 0) {
			TripList.callIntentCategorize(getActivity(), itemsID);
		}
	}

	/**
	 * Dialog edit total
	 */

	private void createDialogEditTotal() {
		subtotal = 0;
		tax = 0;
		discount = 0;
		total = 0;
		dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_receiptdetail_total);

		final TextView txtTotal = (TextView) dialog.findViewById(R.id.txtTotal);

		final TextView txtSubTotal = (TextView) dialog
				.findViewById(R.id.txtSubTotal);

		final TextView txtTax = (TextView) dialog.findViewById(R.id.txtTax);

		final TextView txtDiscount = (TextView) dialog
				.findViewById(R.id.txtDiscount);

		for (tbl_Item objItem : arrItem) {
			subtotal = subtotal + Util.convertFloat(objItem.getAmount());
		}
		tax = Util.convertFloat(this.txtTax.getText().toString().substring(1));

		discount = Util.convertFloat(this.txtDiscount.getText().toString()
				.substring(1));

		total = subtotal + tax - discount;
		txtTax.setText(Util.formatStringFloat(tax) + "");
		txtSubTotal.setText(Util.formatStringFloat(subtotal) + "");
		txtDiscount.setText(Util.formatStringFloat(discount) + "");
		txtTotal.setText(Util.formatStringFloat(total) + "");

		txtTax.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (!Util.validateFloat2Decimal(txtTax.getText().toString())) {
					txtTax.setText(txtTax
							.getText()
							.toString()
							.substring(0,
									txtTax.getText().toString().length() - 1));
				} else {
					float subtotal = Float.valueOf(txtSubTotal.getText()
							.toString());
					float tax = 0;
					if (!"".equals(txtTax.getText().toString())) {
						tax = Util.convertFloat(txtTax.getText().toString());
					}
					float discount = 0;
					if (!"".equals(txtDiscount.getText().toString())) {
						discount = Util.convertFloat(txtDiscount.getText()
								.toString());
					}
					float total = subtotal + tax - discount;
					txtTotal.setText(Util.formatStringFloat(total) + "");
				}

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

		txtDiscount.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (!Util.validateFloat2Decimal(txtDiscount.getText()
						.toString())) {
					txtDiscount
							.setText(txtDiscount
									.getText()
									.toString()
									.substring(
											0,
											txtDiscount.getText().toString()
													.length() - 1));
				} else {
					float subtotal = Float.valueOf(txtSubTotal.getText()
							.toString());
					float tax = 0;
					if (!"".equals(txtTax.getText().toString())) {
						tax = Util.convertFloat(txtTax.getText().toString());
					}
					float discount = 0;
					if (!"".equals(txtDiscount.getText().toString())) {
						discount = Util.convertFloat(txtDiscount.getText()
								.toString());
					}
					float total = subtotal + tax - discount;
					txtTotal.setText(Util.formatStringFloat(total) + "");
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

		LinearLayout llCancel, llSave;
		llCancel = (LinearLayout) dialog.findViewById(R.id.llCancel);
		llSave = (LinearLayout) dialog.findViewById(R.id.llSave);
		llSave.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				// get total and check total # ""
				String total = txtTotal.getText().toString();
				total = "".equals(total) ? "0.00" : total;
				objReceipt.setTotal(total);

				// get total and check subtotal # ""
				String subtotal = txtSubTotal.getText().toString();
				subtotal = "".equals(subtotal) ? "0.00" : subtotal;
				objReceipt.setSubtotal(subtotal);

				// get total and check tax # ""
				String tax = txtTax.getText().toString();
				tax = "".equals(tax) ? "0.00" : tax;
				objReceipt.setTax(tax);

				// get total and check discount # ""
				String discount = txtDiscount.getText().toString();
				discount = "".equals(discount) ? "0.00" : discount;
				objReceipt.setDiscount(discount);
				if (getActivity().getContentResolver().update(
						Contract.CONTENT_URI_RECEIPT,
						objReceipt.getContentValues(),
						tbl_ReceiptDao.Properties.ReceiptID.columnName + " = "
								+ objReceipt.getReceiptID(), null) > 0) {
					addDataUI();
					Utils.hideKeyboard(getContext(), (EditText) txtDiscount);
					Utils.hideKeyboard(getContext(), (EditText) txtTax);
					dialog.dismiss();
				} else {

				}

			}
		});
		llCancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Utils.hideKeyboard(getContext(), (EditText) txtDiscount);
				Utils.hideKeyboard(getContext(), (EditText) txtTax);
				dialog.dismiss();
			}
		});
		dialog.show();

	}

	private void setTextCategorize(String text) {
		dialog.dismiss();
		((TextView) v.findViewById(R.id.txtCategorize)).setText(text);
	}

	/**
	 * display logo merchant and download image receipt
	 */
	private class DisplayLogoMerchant extends AsyncTask<String, Void, Bitmap> {
		ImageView bmImage;

		public DisplayLogoMerchant(ImageView bmImage) {
			this.bmImage = bmImage;
		}

		protected Bitmap doInBackground(String... urls) {
			String urldisplay = urls[0];
			if (urldisplay == null || "".equals(urldisplay)) {
				return null;
			}
			Bitmap mIcon11 = null;
			try {
				InputStream in = new java.net.URL(urldisplay).openStream();
				mIcon11 = BitmapFactory.decodeStream(in);
			} catch (Exception e) {
				e.printStackTrace();
			}

			return mIcon11;
		}

		protected void onPostExecute(Bitmap result) {
			pbLoad.setVisibility(View.GONE);
			llContent.setVisibility(View.VISIBLE);
			bmImage.setImageBitmap(result);
			new DowloadImage().execute("");
		}
	}

	private class DowloadImage extends AsyncTask<String, Void, Bitmap> {

		protected Bitmap doInBackground(String... urls) {
			downloadImage();

			return null;
		}

	}

	private void downloadImage() {
		if (objReceipt != null) {
			int index = objReceipt.getReceiptImage().indexOf(
					Const.FILE_KEY + "");
			if (index == -1 && !"".equals(objReceipt.getReceiptImage())) {
				if (Util.isNetworkActivated(getActivity())) {
					if (NetUtils.DownloadImageFromPath(
							objReceipt.getReceiptImage(),
							objReceipt.getReceiptID() + "")) {
						updateReceipt();
					} else {
						ArrayList<BaseObject> arrBase = new ArrayList<BaseObject>();
						arrBase = NetSupport.validateImageReceipt(objReceipt
								.getReceiptID() + "");
						if (arrBase != null) {
							for (BaseObject objBase : arrBase) {
								String image = objBase.getParam("image");
								if (!"".equals(image)) {
									if (NetUtils.DownloadImageFromPath(image,
											objReceipt.getReceiptID() + "")) {
										updateReceipt();
									}
								}

							}
						}
					}
				} else {
				}
			}

		}
	}

	/**
	 * update image receipt
	 */
	private int updateReceipt() {
		if (objReceipt == null) {
			return 0;
		}
		objReceipt.setReceiptImage(Const.FILE_KEY + objReceipt.getReceiptID());
		if (getActivity() != null) {
			return getActivity().getContentResolver().update(
					Contract.CONTENT_URI_RECEIPT,
					objReceipt.getContentValues(),
					tbl_ReceiptDao.Properties.ReceiptID.columnName + " = "
							+ objReceipt.getReceiptID(), null);
		}
		return 0;

	}

	/**
	 * Get BaseModel
	 */

	protected BaseModel getModel() {
		return ((ReceiptBox) getActivity()).model;
	}

	/**
	 * dialog gÃ¡Â»â€œm 2 lÃ¡Â»Â±a chÃ¡Â»ï¿½n. user cÃƒÂ³ thÃ¡Â»Æ’ chÃ¡Â»ï¿½n
	 * tÃ¡Â»â€ºi phÃ¡ÂºÂ§n chÃ¡Â»Â¥p Ã¡ÂºÂ£nh hoÃ¡ÂºÂ·c user cÃƒÂ³ thÃ¡Â»Æ’
	 * chÃ¡Â»ï¿½n tÃ¡Â»â€ºi sdcard
	 */

	private void createDialogDelete() {
		dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_message);

		final LinearLayout llOk;
		LinearLayout llCancel;
		final TextView txtTitle = ((TextView) dialog
				.findViewById(R.id.txtTitle));
		txtTitle.setText(getString(R.string.delete_receipt));
		String mContent = getString(R.string.are_you_sure_you_want_to_delete_receipts);
		final TextView txtContent = ((TextView) dialog
				.findViewById(R.id.txtContent));
		txtContent.setText(mContent);

		llOk = (LinearLayout) dialog.findViewById(R.id.llOk);

		llCancel = (LinearLayout) dialog.findViewById(R.id.llCancel);

		llOk.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (DatabaseSupport.ruleRecipt(mReceiptID, getActivity())) {
					int row = 0;
					if ("1".equals(objReceipt.getIsCreate())) {
						row = getActivity().getContentResolver().delete(
								Contract.CONTENT_URI_RECEIPT,
								tbl_ReceiptDao.Properties.ReceiptID.columnName
										+ " = " + objReceipt.getReceiptID(),
								null);
					} else {
						objReceipt.setIsDelete("1");
						row = getActivity().getContentResolver().update(
								Contract.CONTENT_URI_RECEIPT,
								objReceipt.getContentValues(),
								tbl_ReceiptDao.Properties.ReceiptID.columnName
										+ " = '" + mReceiptID + "'", null);
					}
					if (row == 1) {
						MenuFragment menuFragment = new MenuFragment();
						menuFragment.resetMenuList(getResources(),
								getActivity());
						Util.pushFragmentReceiptBox(
								new ReceiptFragment(Integer.valueOf(receiptObj
										.getReceiptType()), mCountReceipt,
										numberFilter), getActivity(), "1");
					} else {
						showToast(getString(R.string.this_receipt_is_reported));
					}
					dialog.dismiss();
				} else {
					((TextView) dialog.findViewById(R.id.txtNo))
							.setText(getString(R.string.cancel));
					txtTitle.setText(getString(R.string.title_messsage_receipt_detail_one));
					llOk.setVisibility(View.GONE);
					txtContent
							.setText(getString(R.string.message_error_report_one));
				}
			}
		});

		llCancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		dialog.show();

	}

	/**
	 * dialog gÃ¡Â»â€œm 2 lÃ¡Â»Â±a chÃ¡Â»ï¿½n. user cÃƒÂ³ thÃ¡Â»Æ’ chÃ¡Â»ï¿½n
	 * tÃ¡Â»â€ºi phÃ¡ÂºÂ§n chÃ¡Â»Â¥p Ã¡ÂºÂ£nh hoÃ¡ÂºÂ·c user cÃƒÂ³ thÃ¡Â»Æ’
	 * chÃ¡Â»ï¿½n tÃ¡Â»â€ºi sdcard
	 */

	private void createDialogError(boolean isTrue) {
		dialog = new Dialog(getActivity());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_message);

		LinearLayout llOk, llCancel;
		((TextView) dialog.findViewById(R.id.txtTitle))
				.setText(getString(R.string.message_receipt));
		if (isTrue) {
			((TextView) dialog.findViewById(R.id.txtContent))
					.setText(getString(R.string.message_error_report_one));
		} else {
			((TextView) dialog.findViewById(R.id.txtContent))
					.setText(getString(R.string.message_edit_report_one));
		}

		llOk = (LinearLayout) dialog.findViewById(R.id.llOk);

		llCancel = (LinearLayout) dialog.findViewById(R.id.llCancel);
		llCancel.setVisibility(View.GONE);
		llOk.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

		dialog.show();

	}

}
